package cupk.wudi;

import cupk.wudi.pojo.Animal;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import cupk.wudi.mapper.AnimalMapper;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class MyBatisDemo {


    public static void main(String[] args) throws IOException {
        //1、加载mybatis核心配置文件

        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        //2、获取sqlsession对象
        SqlSession sqlSession=sqlSessionFactory.openSession();

        //3、执行sql
        AnimalMapper animalMapper =sqlSession.getMapper(AnimalMapper.class);
        //先将接口实例化
        //打印全表
        List<Animal> animalList = animalMapper.selectAll();
        System.out.println(animalList);
        //查找单个动物相关信息
        Animal animal = animalMapper.getByName("鲨鱼");
        System.out.println(animal);
        //删除信息
        Integer flag =animalMapper.deleteByName("狮子");

        List<Animal> animalList2 = animalMapper.selectAll();
        System.out.println(flag);
        System.out.println(animalList2);

        Animal elephant=new Animal();
        elephant.setArea("草原");
        elephant.setName("大象");
        elephant.setType("哺乳动物");
        elephant.setNumber(20);
        Integer Inseartflag =animalMapper.addAnimal(elephant);

        List<Animal> animalList3 = animalMapper.selectAll();
        System.out.println(Inseartflag);
        System.out.println(animalList3);

        //4、提交外存
        sqlSession.commit();
        //5、释放资源
        sqlSession.close();
    }
}
